from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt

from lbforum.models import *
from scrapers import *

def update_user(user_name) :
    
    print "Updating info for user", user_name
    if(len(User.objects.filter(username=user_name)) is not 0):
        user = User.objects.filter(username=user_name)[0]
        
        userProfile = user.trust_profile
        totalReviews = 0
        numEbayReviews = 0
        numAirReviews = 0
        numGarReviews = 0
        numSources = 0
        
        if(userProfile.trust_ebay_acct_name != ""):
            print "Found ebay profile, lets do some scraping"
            try:
                scraper = EbayScraper()
                summary = scraper.getSummary(userProfile.trust_ebay_acct_name)
                reviews = scraper.getReviews(userProfile.trust_ebay_acct_name)
                numEbayReviews = update_db(user, userProfile, "eBay", summary, reviews)
                totalReviews += numEbayReviews
                numSources = numSources + 1
            except:
                print "Failed to scrape ebay with account: ", userProfile.trust_ebay_acct_name  
        else:
            userProfile.trust_ebay_avg_score = 0
            userProfile.save()
            
        if(userProfile.trust_gar_acct_name != ""):
            print "Found GetAround profile, lets do some scraping"
            try:
                scraper = GetAroundScraper()
                summary = scraper.getSummary(userProfile.trust_gar_acct_name)
                reviews = scraper.getReviews(userProfile.trust_gar_acct_name)
                numAirReviews = update_db(user, userProfile, "GetAround", summary, reviews) 
                totalReviews += numAirReviews
                numSources = numSources + 1
                
            except:
                print "Failed to scrape GetAround with account: ", userProfile.trust_gar_acct_name  
        else:
            userProfile.trust_gar_avg_score = 0
            userProfile.save()       
            
        if(userProfile.trust_airbnb_acct_name != ""):
            print "Found AirBnb profile, lets do some scraping"
            try:
                scraper = AirBnBScraper()
                summary = scraper.getSummary(userProfile.trust_airbnb_acct_name)
                reviews = scraper.getReviews(userProfile.trust_airbnb_acct_name)   
                numGarReviews = update_db(user, userProfile, "AirBnb", summary, reviews)
                totalReviews += numGarReviews
                numSources = numSources + 1
                  
            except:  
                print "Failed to scrape AirBnb with account: ", userProfile.trust_airbnb_acct_name
        else:
            userProfile.trust_airbnb_avg_score = 0
            userProfile.save() 
                
        eBayAvg = userProfile.trust_ebay_avg_score
        airAvg = userProfile.trust_airbnb_avg_score
        garAvg = userProfile.trust_gar_avg_score
        
        
        
        ebayWeight = float(numEbayReviews) / float(totalReviews)
        airWeight = float(numAirReviews) / float(totalReviews)
        garWeight = float(numGarReviews) / float(totalReviews)
        
        print "Calculating meta score... source count:", numSources
        print "Ebay weight: ", ebayWeight, "(", numEbayReviews, "/", totalReviews, "), Ebay Score: ", eBayAvg
        print "Air weight: ", airWeight, "(", numAirReviews, "/", totalReviews, "), Air Score: ", airAvg
        print "GetAround weight: ", garWeight, "(", numGarReviews, "/", totalReviews, "), GetAround Score: ", garAvg
       
        metaScore = (float(eBayAvg)*ebayWeight + float(airAvg)*airWeight + float(garAvg)*garWeight)
        print "Meta Score: ", metaScore
         
        userProfile.trust_meta_score = int(metaScore)
        userProfile.save()
        
        
    else :
        print "Error: user:", user_name, "not found"  
        
        
def update_db(user, profile, src_type, summary, reviews):
    old_ratings = user.trustratingdata_set.all()
    
    
    reviewsAdded = 0
    
    for review in reviews:
        do_update = True       
        for old_rating in old_ratings:
            if review['reviewer'] == old_rating.trust_reviewer_name and \
                review['review_date'] == old_rating.trust_review_time:
                do_update = False
                break
                    
        if do_update:
            db_rating = TrustRatingData(
                                        user=user,
                                        trust_source_type=src_type,
                                        trust_review_string=review['review'],
                                        trust_reviewer_name=review['reviewer'],
                                        trust_review_score=review['score'],
                                        trust_review_time=review['review_date']
                                        )
            db_rating.save()
            reviewsAdded = reviewsAdded + 1
            
    try:
        x = float(summary['positiveReviews'])
        y = float(summary['totalReviews'])
    except:
        print "FUCK PYTHON: Unexpected error:", sys.exc_info()[0]
    score = ( x / y )*100.0
    score = int(score)  
    print "Score: ", score, "(", x, " / ", y, ")"
    
    if src_type == "eBay":
        profile.trust_ebay_avg_score = score
    elif src_type == "AirBnb":
        profile.trust_airbnb_avg_score = score  
    elif src_type == "GetAround":
        profile.trust_gar_avg_score = score
                
    profile.save()  
                   
    print reviewsAdded, " reviews of ", len(reviews), " added to the db"
    
    return float(summary['totalReviews'])
    
    
    
    
    
    
    
    
    
    
    
    
    
    